package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import pojo.*;
import service.IArticleService;
import service.ICategoryService;
import constant.Constant;
import service.ICommentService;
import util.PageModuleUtil;
import util.Util;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户帖子控制层
 */
@Controller
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private IArticleService articleService;
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private ICommentService commentService;

    @RequestMapping(value = "/{id}/",method = RequestMethod.GET)
    public String goArticleDetailPage(@PathVariable(value = "id",required = true) int id, Model model, HttpServletRequest request){
        //查看请求的帖子是否存在
        Article article = articleService.getArticleById(id);
        if(article==null){
            return "other/404";
        }
        //更新帖子的的阅读量
        if(article.getArticleClickNumber()==null){
            article.setArticleClickNumber(1);
        }else {
            article.setArticleClickNumber(article.getArticleClickNumber()+1);
        }
        articleService.modifyArticleClickNumber(article);
        //获取总的条数
        int count = commentService.getCommentCountByArticleId(article.getArticleId());
        //获取前15个评论
        List<Comment> comments = commentService.getCommentsByArticleId(article.getArticleId(),Constant.DEFAULT_PAGE_SIZE_SMALL,1);
        //判断该帖子是否是问题贴,是否采纳答案
        if(article.getComment()!=null){
            //将被采纳的评论置顶
            int index = -1;
            for (int i = 0 ;i < comments.size();i++){
                if(comments.get(i).getCommentId().equals(article.getComment().getCommentId())){
                    index = i;
                    break;
                }
            }
            if(index!=-1){
                Comment comment = comments.get(index);
                comments.set(index, comments.get(0));
                comments.set(0,comment );
            }
        }
        //获取热议内容
        List<Article> articles = articleService.getArticlesByCommentNumber(1, Constant.DEFAULT_PAGE_SIZE_BIG);
        model.addAttribute("hotda", articles);
        //封装分页
        Page<List<Comment>> page = new Page<>(Constant.DEFAULT_PAGE_SIZE_SMALL, count);
        page.setContent(comments);
        page.setBaseUrl("/article/"+id);
        page.setAdditionalUrl("page");
        model.addAttribute("article",article );
        model.addAttribute("page",page );
        PageModuleUtil.set(request,Constant.PAGE_JIE );
        //通用数据
        Util.setGeneralDataForView(categoryService,model );
        return "jie/detail";
    }
    @RequestMapping(value = "/{id}/page/{pageCurrent}/")
    public String goArticleDetailPageNumber(@PathVariable(value = "id",required = true) int id, @PathVariable(value = "pageCurrent") int pageCurrent, Model model, HttpServletRequest request){
        //查看是否存在该帖子
        Article article = articleService.getArticleById(id);
        if(article==null){
            return "redirect:/*";
        }
        //获取总的条数
        int count = commentService.getCommentCountByArticleId(article.getArticleId());
        //获取前15个评论
        List<Comment> comments = commentService.getCommentsByArticleId(article.getArticleId(),Constant.DEFAULT_PAGE_SIZE_SMALL, pageCurrent);
        //封装分页
        Page<List<Comment>> page = new Page<>(Constant.DEFAULT_PAGE_SIZE_SMALL, count);
        page.setContent(comments);
        page.setPageCurrent(pageCurrent);
        page.setBaseUrl("/article/"+id);
        page.setAdditionalUrl("page");
        model.addAttribute("article",article );
        model.addAttribute("page",page );
        PageModuleUtil.set(request,Constant.PAGE_JIE );
        //通用数据
        Util.setGeneralDataForView(categoryService,model );
        return "jie/detail";
    }
//    @RequestMapping(value = "/{id}/page/{pageCurrent}/{item:\\Sitem-\\d+}")
//    public String goArticleDetailPageNumber(@PathVariable(value = "id",required = true) int id, @PathVariable(value = "pageCurrent") int pageCurrent,@PathVariable(value = "item",required = false) String item, Model model, HttpServletRequest request){
//        //查看是否存在该帖子
//        Article article = articleService.getArticleById(id);
//        if(article==null){
//            return "other/404";
//        }
//        //是否是查看消息
//        String requestURI = String.valueOf(request.getRequestURL());
//        if(requestURI.contains("#item-")){
//            String[] split = requestURI.split("-");
//            int commentId = Integer.parseInt(split[1]);
//            Comment comment = new Comment();
//            comment.setCommentId(commentId);
//            comment.setCommentStatus((byte) 1);
//            commentService.modifyCommentByCommentId(comment);
//        }
//        //获取总的条数
//        int count = commentService.getCommentCountByArticleId(article.getArticleId());
//        //获取前15个评论
//        List<Comment> comments = commentService.getCommentsByArticleId(article.getArticleId(),Constant.DEFAULT_PAGE_SIZE_SMALL, pageCurrent);
//        //封装分页
//        Page<List<Comment>> page = new Page<>(Constant.DEFAULT_PAGE_SIZE_SMALL, count);
//        page.setContent(comments);
//        page.setPageCurrent(pageCurrent);
//        page.setBaseUrl("/article/"+id);
//        page.setAdditionalUrl("page");
//        model.addAttribute("article",article );
//        model.addAttribute("page",page );
//        PageModuleUtil.set(request,Constant.PAGE_JIE );
//        //通用数据
//        Util.setGeneralDataForView(categoryService,model );
//        return "jie/detail";
//    }
    @RequestMapping(value = "/add/",method = RequestMethod.GET)
    public String goAddArticlePage(Model model, HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            return "redirect:/user/login/";
        }
        //获取用户能够操作的帖子类型
        //获取用户的角色类型
        Integer roleId = user.getUserRoleId();
        //获取该角色能够操作的帖子类型
        List<Category> categories = categoryService.getCategoriesByRoleId(roleId);
        model.addAttribute("categories", categories);
        //设置全局配置
        PageModuleUtil.set(request,Constant.PAGE_JIE);
        return "jie/add";
    }
    @ResponseBody
    @RequestMapping(value = "/add/",method = RequestMethod.POST)
    public Map addArticle(Article article,String vercode,HttpServletRequest request){
        Map map = new HashMap();
        String code = (String) request.getSession().getAttribute("vercode");
        if(vercode==null||!code.equals(vercode)){
            map.put("status",1 );
            map.put("msg","验证码不通过" );
            return map;
        }
        if(article==null){
            map.put("status",1);
            map.put("msg","帖子内容丢失");
            return map;
        }
        article.setArticleBuildDate(new Date());
        article.setArticleUpdateDate(new Date());
        int i = articleService.addArticle(article);
        if(i==1){
            map.put("status",0 );
            map.put("action","/" );
            return map;
        }
        map.put("status",1 );
        map.put("msg","贴子提交失败" );
        return map;
    }

    @RequestMapping(value = "/edit/{articleId}",method = RequestMethod.GET)
    public String goEditArticlePage(@PathVariable("articleId") int articleId,HttpServletRequest request,Model model){
        User user = (User) request.getSession().getAttribute("user");
        Article article = articleService.getArticleById(articleId);
        if(user==null){
            model.addAttribute("msg","无权限" );
            return "common/tips";
        }
        if(article==null){
            return "other/404";
        }
        if(!article.getArticleOwner().equals(user.getUserId())||article.getArticleOver()==1){
            model.addAttribute("msg","无权限" );
            return "common/tips";
        }
        model.addAttribute("article",article );
        Util.setGeneralDataForView(categoryService,model );
        return "jie/edit";
    }
    @ResponseBody
    @RequestMapping(value = "/edit/{articleId}",method = RequestMethod.POST)
    public Map doEditArticlePage(Article article,HttpServletRequest request,Model model){
        Map map = new HashMap();
        article.setArticleUpdateDate(new Date());
        int i = articleService.modifyArticleByArticleId(article);
        if(i==1){
            map.put("status",0 );
            map.put("msg","编辑成功" );
            map.put("action","/article/"+article.getArticleId()+"/" );
            return map;
        }
        map.put("status",1 );
        map.put("msg","编辑失败" );
        return map;
    }
}
